<!--
 * @Author: typ
 * @Date: 2025-01-15 10:15:08
 * @LastEditors: typ
 * @LastEditTime: 2025-01-17 16:18:14
 * @FilePath: /720Manage-vite/src/views/model3D/editModel.vue
 * @Description: 3D模型编辑页面，用于展示和编辑3D模型
-->
<template>
  <!-- 页面主容器 -->
  <div class="box">
    <el-container>
      <!-- 顶部导航栏 -->
      <el-header>
        <div class="header-left">
          <el-button style="color: #fff;" link icon="ArrowLeft" @click="handleBack">返回</el-button>
        </div>
        <span class="model-name">{{ modelData?.name }}</span>
        <div class="header-right">
          <el-button style="color: #A9A9A9;" text icon="CloseBold" @click="handleReset">重置</el-button>
          <el-button style="color: #A9A9A9;" text icon="Collection" @click="handleSave">保存</el-button>
        </div>
      </el-header>

      <!-- 主体内容区域 -->
      <el-container>
        <!-- 左侧设置面板 -->
        <el-aside width="395px" style="overflow: hidden;">
          <el-tabs type="border-card" v-model="activeName">
            <!-- 基础设置面板 -->
            <el-tab-pane label="设置" name="setting">
              <div class="setting-box">
                <el-collapse v-model="basicsActiveName">
                  <!-- 通用设置面板：控制模型旋转 -->
                  <el-collapse-item :title="general.title" :name="'general'">
                    <!-- 原有的旋转控制 -->
                    X轴旋转<el-slider v-model="general.x" :min="-180" :max="180" @input="updateModelRotation" />
                    Y轴旋转<el-slider v-model="general.y" :min="-180" :max="180" @input="updateModelRotation" />
                    Z轴旋转<el-slider v-model="general.z" :min="-180" :max="180" @input="updateModelRotation" />
                  </el-collapse-item>

                  <!-- 色调映射设置：控制模型外观 -->
                  <el-collapse-item :title="toneMapping.title" :name="toneMapping.type">
                    亮度<el-slider v-model="toneMapping.brightness" :step="0.01" :min="0" :max="3" />
                    饱和度<el-slider v-model="toneMapping.saturation" :step="0.01" :min="0" :max="3" />
                    对比度<el-slider v-model="toneMapping.contrast" :step="0.01" :min="0" :max="2" />
                  </el-collapse-item>

                  <!-- 视角设置：控制相机参数 -->
                  <el-collapse-item :title="view.title" :name="view.type">
                    视场角(FOV)<el-slider v-model="view.fov" :min="1" :max="179" />
                    近景可视范围<el-slider v-model="view.near" :min="0.1" :max="100" />
                    远景可视范围<el-slider v-model="view.far" :min="100" :max="1000" />
                  </el-collapse-item>
                </el-collapse>
              </div>
            </el-tab-pane>

            <!-- 其他功能标签页 -->
            <!-- <el-tab-pane label="灯光">灯光</el-tab-pane> -->
            <!-- <el-tab-pane label="图片">图片</el-tab-pane> -->
            <!-- <el-tab-pane label="后期">后期</el-tab-pane> -->
            <el-tab-pane label="标注" name="annotation">
              <div class="annotation-box">
                <div v-if="annotations.length === 0" class="annotation-box-title">
                  <div>1.双击模型添加标注</div>
                  <div>2.单击标注进行编辑</div>
                  <div>3.鼠标移入标注预览</div>
                </div>
                <div v-else class="annotation-box-content">
                  <div class="annotation-list">
                    <div v-for="(annotation, index) in annotations" :key="annotation.id" class="annotation-item">
                      <div class="annotation-item-header">
                        <span class="annotation-title">{{ annotation.title }}</span>
                        <div class="annotation-actions">
                          <el-button type="text" @click="toggleAnnotationVisibility(index)">
                            <el-icon>
                              <Hide v-if="!annotation.visible" />
                              <View v-else />
                            </el-icon>
                          </el-button>
                          <el-button type="text" @click="editAnnotation(index)">
                            <el-icon>
                              <Edit />
                            </el-icon>
                          </el-button>
                          <el-button type="text" @click="deleteAnnotation(index)">
                            <el-icon>
                              <Delete />
                            </el-icon>
                          </el-button>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            <!-- <el-tab-pane label="测量" name="measurement">测量</el-tab-pane> -->
          </el-tabs>
        </el-aside>

        <!-- 右侧3D模型展示区域 -->
        <el-main style="padding: 0px;">
          <div class="model-item">
            <!-- Three.js渲染容器 -->
            <div id="model-viewer" ref="modelContainer" v-loading="loading" element-loading-text="模型加载中..."
              element-loading-background="rgba(0, 0, 0, 1)" @dblclick="handleAddAnnotation">
              <!-- 添加标注点标记 -->
              <div v-for="(annotation, index) in annotations" :key="annotation.id" v-show="annotation.visible"
                class="annotation-marker" :style="getAnnotationPosition(annotation.position)"
                @mouseenter="showTooltip(index)" @mouseleave="hideTooltip(index)"
                @click.stop="handleAnnotationClick(index)">
                {{ index + 1 }}
                <!-- 添加悬浮提示框 -->
                <div v-show="annotation.showTooltip" class="annotation-tooltip">
                  <div class="tooltip-title">{{ annotation.title }}</div>
                  <div class="tooltip-content">{{ annotation.content }}</div>
                </div>
              </div>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>
  </div>

  <!-- 添加标注弹窗 -->
  <el-dialog :modal="false" v-model="annotationDialog" :title="editingAnnotationIndex === -1 ? '添加标注' : '编辑标注'"
    width="500px" destroy-on-close>
    <el-form :model="annotationForm" ref="annotationForms" label-width="80px">
      <el-form-item label="标题" prop="title" :rules="{
        required: true,
        message: `请输入标题`,
        trigger: 'blur',
      }">
        <el-input clearable placeholder="请输入" v-model="annotationForm.title" maxlength="20" show-word-limit />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <el-input clearable placeholder="请输入" v-model="annotationForm.content" type="textarea" :rows="4" maxlength="200"
          show-word-limit />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="closeAnnotationDialog">取消</el-button>
      <el-button type="primary" @click="saveAnnotation">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
// 导入所需的依赖
import { onMounted, onBeforeUnmount, ref, toRefs, watch, computed } from 'vue';
import * as THREE from 'three';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { getModel, getModelById } from '@/api/model';
import { useRouter, useRoute } from 'vue-router';

// 初始化路由和全局实例
const router = useRouter()
const route = useRoute()

const { proxy } = getCurrentInstance()
const modelContainer = ref(null)
const loading = ref(true)
let basicsActiveName = ref('general')
let activeName = ref('setting')
// 基础设置配置对象
let basicsConfig = reactive({
  // 通用设置：控制模型旋转
  general: {
    title: '通用设置',
    isTrimm: false,
    x: 0,
    y: 0,
    z: 0,
  },
  // 色调映射：控制模型外观
  toneMapping: {
    type: 'toneMapping',
    title: '色调映射',
    brightness: 1,
    saturation: 0.8,
    contrast: 1,
  },
  // 视角设置：控制相机参数
  view: {
    type: 'view',
    title: '观看设置',
    fov: 45,
    near: 0.1,
    far: 500,
  }
})
const annotations = ref([]) // 存储标注数据
const annotationDialog = ref(false) // 控制标注弹窗
const annotationForm = ref({ // 标注表单数据
  title: '',
  content: '',
  position: null, // 存储标注点的3D位置
})
const editingAnnotationIndex = ref(-1) // 当前编辑的标注索引
const modelData = ref({}) // 模版数据
// 解构配置对象为响应式引用
const { view, general, toneMapping } = toRefs(basicsConfig)

// 返回按钮处理函数
const handleBack = () => {
  router.back()
}

// 保存按钮处理函数
const handleSave = () => {
  proxy.$modal.msgSuccess('保存成功')
}

// Three.js相关变量声明
let scene, camera, renderer, controls, model

// 在 script setup 中添加网格工具的引用
let gridHelper, axesHelper

// 监听视角参数变化
watch(() => [
  view.value.fov,
  view.value.near,
  view.value.far
], () => {
  updateCameraParams()
}, { deep: true })

// 监听色调映射值变化
watch(() => [
  toneMapping.value.brightness,
  toneMapping.value.saturation,
  toneMapping.value.contrast
], () => {
  updateToneMapping()
}, { deep: true })

// 初始化Three.js场景
const initThree = async () => {
  try {
    loading.value = true
    const res = await getModelById(route.query.id);
    modelData.value = res.data;
    let path = null;
    if (res.data?.previewFileName) {
      path = JSON.parse(res.data.previewFileName);
    }
    // 获取模型相关资源
    const url = await getModel({ originalName: path.gltf })
    const binUrl = await getModel({ originalName: path.bin })
    const imgUrl = await getModel({ originalName: path.jpg })
    const newUrl = import.meta.env.VITE_APP_PIC_BASE_API + '/' + url.split('/').slice(3).join('/');
    const newBinUrl = import.meta.env.VITE_APP_PIC_BASE_API + '/' + binUrl.split('/').slice(3).join('/');
    const newImgUrl = import.meta.env.VITE_APP_PIC_BASE_API + '/' + imgUrl.split('/').slice(3).join('/');
    // 创建场景
    scene = new THREE.Scene()
    scene.background = new THREE.Color(0x333333)

    // 创建相机
    camera = new THREE.PerspectiveCamera(
      view.value.fov,
      modelContainer.value.clientWidth / modelContainer.value.clientHeight,
      view.value.near,
      view.value.far
    )
    camera.position.set(0, 5, 10)
    camera.lookAt(0, 0, 0)

    // 创建渲染器
    renderer = new THREE.WebGLRenderer({
      antialias: true,
      alpha: true,
      preserveDrawingBuffer: true
    })
    renderer.setSize(modelContainer.value.clientWidth, modelContainer.value.clientHeight)
    renderer.setPixelRatio(window.devicePixelRatio)
    renderer.toneMapping = THREE.ACESFilmicToneMapping
    renderer.toneMappingExposure = toneMapping.value.brightness
    renderer.outputEncoding = THREE.sRGBEncoding
    renderer.gammaOutput = true
    renderer.gammaFactor = 2.2
    renderer.shadowMap.enabled = true

    // 将渲染器添加到DOM
    modelContainer.value.appendChild(renderer.domElement)

    // 创建控制器
    controls = new OrbitControls(camera, renderer.domElement)
    controls.enableDamping = true
    controls.dampingFactor = 0.05
    controls.screenSpacePanning = false
    controls.minDistance = 1
    controls.maxDistance = 500
    controls.maxPolarAngle = Math.PI / 1.5

    // 添加光源
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.5)
    scene.add(ambientLight)

    const directionalLight = new THREE.DirectionalLight(0xffffff, 1)
    directionalLight.position.set(5, 5, 5)
    directionalLight.castShadow = true
    scene.add(directionalLight)

    // 添加网格图工具
    gridHelper = new THREE.GridHelper(10, 10)
    gridHelper.visible = activeName.value === 'setting'
    scene.add(gridHelper)

    // 添加坐标轴辅助工具
    axesHelper = new THREE.AxesHelper(5)
    axesHelper.visible = activeName.value === 'setting'
    scene.add(axesHelper)

    // 加载模型
    const loader = new GLTFLoader()
    const manager = new THREE.LoadingManager()

    // 配置资源加载器
    manager.setURLModifier((resource) => {
      if (resource.endsWith('.bin')) {
        return newBinUrl
      } else if (resource.indexOf('quality') > -1) {
        return newImgUrl
      }
      return resource
    })

    loader.manager = manager

    // 加载GLTF模型
    loader.load(
      newUrl,
      (gltf) => {
        model = gltf.scene

        // 设置模型阴影并保存原始材质
        model.traverse((child) => {
          if (child.isMesh) {
            child.castShadow = true
            child.receiveShadow = true
            // 保存原始材质
            child._originalMaterial = child.material.clone()
          }
        })

        // 调整模型位置和大小
        const box = new THREE.Box3().setFromObject(model)
        const center = box.getCenter(new THREE.Vector3())
        const size = box.getSize(new THREE.Vector3())

        const maxDim = Math.max(size.x, size.y, size.z)
        const scale = 5 / maxDim
        model.scale.setScalar(scale)

        model.position.sub(center.multiplyScalar(scale))

        scene.add(model)

        // 调整相机位置
        // const distance = maxDim * scale * 2
        camera.position.set(0, 2, 15)
        controls.target.set(0, 0, 0)

        // 更新相机参数
        updateCameraParams();
        controls.update()

        // 应用初始设置
        updateModelRotation()
        updateToneMapping()

        loading.value = false
      },
      (xhr) => {
        const progress = Math.floor((xhr.loaded / xhr.total) * 100)
        console.log(`Loading progress: ${progress}%`)
      },
      (error) => {
        console.error('Error loading model:', error)
        loading.value = false
        proxy.$modal.msgError('模型加载失败')
      }
    )

    // 动画循环
    const animate = () => {
      requestAnimationFrame(animate)
      controls.update()

      // 更新所有标注点的位置
      annotations.value.forEach(annotation => {
        if (annotation.position) {
          const pos = getAnnotationPosition(annotation.position)
          annotation._screenPosition = pos
        }
      })

      renderer.render(scene, camera)
    }
    animate()

  } catch (error) {
    console.error('初始化失败:', error)
    loading.value = false
    proxy.$modal.msgError('场景初始化失败')
  }
}
// 添加更新相机参数的函数
const updateCameraParams = () => {
  if (!camera) return

  // 更新相机参数
  camera.fov = view.value.fov
  camera.near = view.value.near
  camera.far = view.value.far

  // 更新相机的投影矩阵
  camera.updateProjectionMatrix()
}
//  首先创建自定义着色器
const createCustomShader = (originalMaterial) => {
  // 自定义顶点着色器
  const vertexShader = `
    varying vec2 vUv;
    varying vec3 vNormal;
    varying vec3 vViewPosition;

    void main() {
      vUv = uv;
      vNormal = normalize(normalMatrix * normal);
      vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);
      vViewPosition = -mvPosition.xyz;
      gl_Position = projectionMatrix * mvPosition;
    }
  `

  // 自定义片元着色器
  const fragmentShader = `
    uniform sampler2D baseTexture;
    uniform float saturation;
    uniform float contrast;
    uniform vec3 baseColor;
    uniform float brightness;
    
    varying vec2 vUv;
    varying vec3 vNormal;
    varying vec3 vViewPosition;

    // 计算饱和度
    vec3 adjustSaturation(vec3 color, float saturation) {
      float grey = dot(color, vec3(0.299, 0.587, 0.114));
      return mix(vec3(grey), color, saturation);
    }

    // 计算对比度
    vec3 adjustContrast(vec3 color, float contrast) {
      return (color - 0.5) * contrast + 0.5;
    }

    void main() {
      // 获取基础颜色
      vec4 texColor = texture2D(baseTexture, vUv);
      vec3 color = texColor.rgb * baseColor;

      // 应用饱和度
      color = adjustSaturation(color, saturation);

      // 应用对比度
      color = adjustContrast(color, contrast);

      // 应用亮度
      color *= brightness;

      gl_FragColor = vec4(color, texColor.a);
    }
  `

  // 创建自定义材质
  return new THREE.ShaderMaterial({
    uniforms: {
      baseTexture: { value: originalMaterial.map },
      saturation: { value: toneMapping.value.saturation },
      contrast: { value: toneMapping.value.contrast },
      brightness: { value: toneMapping.value.brightness },
      baseColor: { value: originalMaterial.color }
    },
    vertexShader: vertexShader,
    fragmentShader: fragmentShader,
    transparent: originalMaterial.transparent,
    side: originalMaterial.side
  })
}

// 更新色调映射函数
const updateToneMapping = () => {
  if (!model || !renderer) return

  // 更新渲染器的曝光度（全局亮度）
  renderer.toneMappingExposure = toneMapping.value.brightness

  // 更新模型材质
  model.traverse((child) => {
    if (child.isMesh && child.material) {
      try {
        // 如果没有自定义着色器材质，创建一个
        if (!child._customMaterial) {
          // 保存原始材质
          child._originalMaterial = child.material.clone()
          // 创建自定义着色器材质
          child._customMaterial = createCustomShader(child._originalMaterial)
          // 应用自定义材质
          child.material = child._customMaterial
        }

        // 更新着色器uniforms
        child.material.uniforms.brightness.value = toneMapping.value.brightness
        child.material.uniforms.saturation.value = toneMapping.value.saturation
        child.material.uniforms.contrast.value = toneMapping.value.contrast

        // 标记材质需要更新
        child.material.needsUpdate = true
      } catch (error) {
        console.error('Error updating material:', error)
      }
    }
  })
}



// 处理窗口大小变化
const handleResize = () => {
  if (!camera || !renderer || !modelContainer.value) return

  // 更新相机宽高比
  camera.aspect = modelContainer.value.clientWidth / modelContainer.value.clientHeight
  camera.updateProjectionMatrix()

  // 更新渲染器尺寸
  renderer.setSize(modelContainer.value.clientWidth, modelContainer.value.clientHeight)
}

// 更新模型旋转
const updateModelRotation = () => {
  if (!model) return
  const xRad = THREE.MathUtils.degToRad(general.value.x)
  const yRad = THREE.MathUtils.degToRad(general.value.y)
  const zRad = THREE.MathUtils.degToRad(general.value.z)
  model.rotation.set(xRad, yRad, zRad)
}

// 旋转值变化
watch(() => [general.value.x, general.value.y, general.value.z], () => {
  updateModelRotation()
}, { deep: true })

// 修改重置函数
const handleReset = async () => {
  if (!model) return

  // 先重置材质
  await new Promise(resolve => {
    model.traverse((child) => {
      if (child.isMesh) {
        if (child._originalMaterial) {
          child.material = child._originalMaterial.clone()
          child.material.needsUpdate = true
        }
        // 清理自定义材质
        if (child._customMaterial) {
          child._customMaterial.dispose()
          delete child._customMaterial
        }
      }
    })
    resolve()
  })

  // 清空所有标注数据
  annotations.value.forEach(annotation => {
    // 如果有3D对象，从场景中移除
    if (annotation.marker) {
      scene.remove(annotation.marker)
    }
    if (annotation.tooltip) {
      scene.remove(annotation.tooltip)
    }
  })
  // 清空标注数组
  annotations.value = []

  // 然后重置所有参数
  general.value.x = 0
  general.value.y = 0
  general.value.z = 0
  updateModelRotation()

  // 重置色调映射
  toneMapping.value.brightness = 1
  toneMapping.value.saturation = 0.8
  toneMapping.value.contrast = 1

  // 重置视角参数
  view.value.fov = 45
  view.value.near = 0.1
  view.value.far = 500

  // 最后更新所有效果
  updateCameraParams()
  updateToneMapping()

  // 强制渲染一帧
  renderer.render(scene, camera)
  proxy.$modal.msgSuccess('重置成功')
}



// 添加标注点的处理函数
const handleAddAnnotation = (event) => {
  if (activeName.value !== 'annotation') return

  // 获取鼠标点击位置
  const rect = event.target.getBoundingClientRect()
  const x = ((event.clientX - rect.left) / rect.width) * 2 - 1
  const y = -((event.clientY - rect.top) / rect.height) * 2 + 1

  // 创建射线
  const raycaster = new THREE.Raycaster()
  const mouse = new THREE.Vector2(x, y)
  raycaster.setFromCamera(mouse, camera)

  // 检测射线与模型的交点
  const intersects = raycaster.intersectObject(model, true)

  if (intersects.length > 0) {
    // 存储点击位置
    annotationForm.value.position = intersects[0].point.clone();
    // 打开标注弹窗
    annotationDialog.value = true
  }
}

// 关闭标注弹窗
const closeAnnotationDialog = () => {
  editingAnnotationIndex.value = -1
  annotationForm.value = { title: '', content: '', position: null }
  proxy.$refs['annotationForms'].resetFields()
  annotationDialog.value = false
}

// 添加标注悬浮状态控制
const showTooltip = (index) => {
  annotations.value[index].showTooltip = true
}

const hideTooltip = (index) => {
  annotations.value[index].showTooltip = false
}

// 修改保存标注函数
const saveAnnotation = () => {
  proxy.$refs['annotationForms'].validate((valid) => {
    if (valid) {
      const newAnnotation = {
        id: annotationForm.value.id || Date.now(),
        title: annotationForm.value.title,
        content: annotationForm.value.content,
        position: annotationForm.value.position,
        visible: true,
        showTooltip: false // 添加tooltip显示状态
      }

      if (!annotationForm.value.id) {
        annotations.value.push(newAnnotation)
      } else {
        const index = annotations.value.findIndex(a => a.id === annotationForm.value.id)
        if (index !== -1) {
          annotations.value[index] = newAnnotation
        }
      }

      annotationForm.value = { title: '', content: '', position: null }
      annotationDialog.value = false
      editingAnnotationIndex.value = -1
    }
  })
}

// 编辑标注
const editAnnotation = (index) => {
  const annotation = annotations.value[index]
  annotationForm.value = { ...annotation }
  editingAnnotationIndex.value = index
  annotationDialog.value = true
}

// 删除标注
const deleteAnnotation = (index) => {
  annotations.value.splice(index, 1)
}

// 切换标注可见性
const toggleAnnotationVisibility = (index) => {
  annotations.value[index].visible = !annotations.value[index].visible
}

// 添加网格工具显示控制函数
const toggleHelpers = (show) => {
  if (gridHelper && axesHelper) {
    gridHelper.visible = show
    axesHelper.visible = show
  }
}

// 监听标签页切换
watch(() => activeName.value, (newValue) => {
  // 在标注模式下隐藏网格工具，其他模式显示
  toggleHelpers(newValue === 'setting')
}, { immediate: true })

// 组件生命周期钩子
onMounted(() => {
  initThree()
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)

  // 清理网格工具
  if (gridHelper) {
    gridHelper.dispose()
  }
  if (axesHelper) {
    axesHelper.dispose()
  }

  // 清理材质
  if (model) {
    model.traverse((child) => {
      if (child.isMesh) {
        if (child._customMaterial) {
          child._customMaterial.dispose()
        }
        if (child._originalMaterial) {
          child._originalMaterial.dispose()
        }
        if (child.material) {
          child.material.dispose()
        }
      }
    })
  }

  if (renderer) {
    renderer.dispose()
    modelContainer.value?.removeChild(renderer.domElement)
  }
})

// 计算标注点的屏幕坐标
const getAnnotationPosition = (position) => {
  if (!position || !camera || !modelContainer.value) return { display: 'none' }

  // 将3D坐标转换为屏幕坐标
  const vector = position.clone()
  vector.project(camera)

  // 转换为CSS坐标
  const x = (vector.x + 1) / 2 * modelContainer.value.clientWidth
  const y = (-vector.y + 1) / 2 * modelContainer.value.clientHeight

  // 检查点是否在视野内
  if (vector.z > 1) {
    return { display: 'none' }
  }

  return {
    left: `${x}px`,
    top: `${y}px`
  }
}

// 在动画循环中添加标注位置更新
const animate = () => {
  requestAnimationFrame(animate)
  controls.update()

  // 更新所有标注点的位置
  annotations.value.forEach(annotation => {
    if (annotation.position) {
      const pos = getAnnotationPosition(annotation.position)
      annotation._screenPosition = pos
    }
  })

  renderer.render(scene, camera)
}

// 添加标注点的样式
const annotationMarkerStyle = computed(() => {
  return {
    position: 'absolute',
    width: '24px',
    height: '24px',
    backgroundColor: '#409EFF',
    color: '#fff',
    borderRadius: '50%',
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    cursor: 'pointer',
    fontSize: '12px',
    transform: 'translate(-50%, -50%)',
    zIndex: 1000,
    pointerEvents: 'auto'
  }
})

// 在 script setup 中添加处理函数
const handleAnnotationClick = (index) => {
  // 阻止事件冒泡
  event.stopPropagation()

  const annotation = annotations.value[index]
  // 复制标注数据到表单
  annotationForm.value = {
    id: annotation.id,
    title: annotation.title,
    content: annotation.content,
    position: annotation.position
  }
  editingAnnotationIndex.value = index
  annotationDialog.value = true
}
</script>

<style lang="scss" scoped>
.box {
  width: 100%;
  height: 100%;
}

::v-deep .el-header {
  background-color: #333333;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;


}

.model-name {
  font-size: 18px;
}

::v-deep .el-container {
  height: calc(100vh - 60px);

  .el-aside {
    height: calc(100vh - 60px);
    padding: 0px;
    border-radius: 0px;
    background-color: #595959;
    color: #fff;
  }
}

// 模型项样式
.model-item {
  width: 100%;
  height: 100%;
}

// Three.js渲染容器样式
#model-viewer {
  width: 100%;
  height: calc(100vh - 60px);
  background-color: #f0f0f0; // 背景色
}

::v-deep .el-tabs {
  height: calc(100vh - 60px);
  background-color: #111111;
  padding: 0px;
  color: #fff;

  .setting-box {
    height: 100%;
    overflow: auto;
  }

  .annotation-box {
    height: 100%;
    background-color: #333333;

    .annotation-list {
      display: flex;
      flex-direction: column;

      .annotation-item {
        padding: 12px;

        &:hover {
          background-color: #666;
        }
      }


      .annotation-item-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .annotation-box-title {
      font-size: 12px;
      padding: 12px;
    }
  }

  .el-tabs__nav-scroll {
    background-color: black;
  }

  .is-active {
    color: #fff !important;
    background-color: #595959 !important;
  }

  .el-tab-pane {
    height: 100%;
    overflow: auto;
  }

  .el-tabs__content {
    padding: 0px;
    height: calc(100vh - 60px - 36px);
    overflow: auto;
  }
}

::v-deep .el-collapse {

  .el-collapse-item__header {
    color: #fff;
    padding-left: 12px;
    font-size: 14px;
    background-color: #595959;
  }

  .el-collapse-item__wrap {
    border: none;
  }

  .el-collapse-item__content {
    background-color: #111111;
    color: #fff;
    font-size: 14px;
    padding: 16px;
  }
}

// 添加滑块样式
::v-deep .el-slider {
  margin: 10px 0;
  width: 90%; // 调整滑块宽度

  .el-slider__runway {
    background-color: #333;
  }

  .el-slider__bar {
    background-color: #409EFF;
  }

  .el-slider__button {
    border-color: #409EFF;
  }
}

// 添加标注点样式
.annotation-marker {
  position: absolute;
  width: 24px;
  height: 24px;
  background-color: #409EFF;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  transform: translate(-50%, -50%);
  z-index: 1000;
  transition: all 0.3s ease;

  &:hover {
    transform: translate(-50%, -50%) scale(1.2);
    background-color: #66b1ff;
  }

  .annotation-tooltip {
    position: absolute;
    top: -60px;
    left: 50%;
    transform: translateX(-50%);
    background-color: rgba(0, 0, 0, 0.8);
    color: white;
    padding: 8px 12px;
    border-radius: 4px;
    min-width: 120px;
    white-space: nowrap;
    z-index: 1001;
    pointer-events: none;

    &::after {
      content: '';
      position: absolute;
      bottom: -5px;
      left: 50%;
      transform: translateX(-50%);
      border-width: 5px 5px 0;
      border-style: solid;
      border-color: rgba(0, 0, 0, 0.8) transparent transparent;
    }

    .tooltip-title {
      font-weight: bold;
      font-size: 14px;
      margin-bottom: 4px;
    }

    .tooltip-content {
      font-size: 12px;
      max-width: 200px;
      overflow-wrap: break-word;
    }
  }
}

// 修改model-viewer样式，添加相对定位
#model-viewer {
  width: 100%;
  height: calc(100vh - 60px);
  background-color: #f0f0f0;
  position: relative; // 添加这行
  overflow: hidden; // 添加这行
}
</style>
